var gulp = require('gulp'),
    sourcemaps = require('gulp-sourcemaps'),
	compass = require('gulp-compass'),
    server = require('gulp-server-livereload'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    htmlreplace = require('gulp-html-replace'),
    rename = require('gulp-rename'),
    os = require('os'),

    cur_ip = os.networkInterfaces().en0[1].address;

gulp.task('compass', function() {
    gulp.src('css/sass/style.scss')
        .pipe(compass({
            config_file: './css/config.rb',
            css: 'css/stylesheets/',
            sass: 'css/sass/',
            sourcemap: true,
            style: 'compressed',
            comments: false,
            time: true
        }))
        .on('error', function(error) {
            console.log(error);
            this.emit('end');
        })
        .pipe(sourcemaps.write('css/stylesheets/'))
        .pipe(gulp.dest('css/stylesheets/'));
});

gulp.task('default', ['webserver'], function() {
    gulp.watch(['css/sass/common.scss',
                'css/sass/style.scss'], ['compass']);
});

gulp.task('webserver', function() {
  gulp.src('./')
    .pipe(server({
        host: cur_ip,
        directoryListing: {enable: true},
        livereload: {
            enable: true,
            filter: function(filePath, cb) {
                cb( !(/node_modules/.test(filePath)) );
            }
        }
    }));
});

gulp.task('dest', function(){
    gulp.src('style/sass/style.scss')
        .pipe(compass({
            config_file: './style/config.rb',
            css: 'style/stylesheets/',
            sass: 'style/sass/',
            sourcemap: true,
            style: 'compressed',
            comments: false,
            time: true
        }))
        .on('error', function(error) {
            console.log(error);
            this.emit('end');
        })
        .pipe(sourcemaps.write('dest/style/stylesheets/'))
        .pipe(gulp.dest('dest/style/stylesheets'));

    gulp.src(['javascript/lib.js', 'javascript/lib-directive-fun.js'])
        .pipe(concat('lib.js'))
        .pipe(uglify({mangle: false}))
        .pipe(gulp.dest('dest/javascript'));

    gulp.src(['javascript/angular.min.js'])
        .pipe(uglify({mangle: false}))
        .pipe(gulp.dest('dest/javascript'));

    gulp.src('fonts/*')
        .pipe(gulp.dest('dest/fonts'));

    gulp.src('index.html')
        .pipe(htmlreplace({
            'dev_js' : 'javascript/lib.js'
        }))
        .pipe(rename('web.html'))
        .pipe(gulp.dest('dest'));
});
